package validator.mail;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class MailValidator
 */
@WebServlet("/MailValidator")
public class MailValidator extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final String MAIL_REGEX = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MailValidator() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String mail = request.getParameter("mail");
		System.out.println("Mail validation request for " + mail);

		String responseMessage = "Email not valid. Valid format is <name>@<domain>.<tld>";
		if (mail == null) {
			responseMessage = "Email cannot be null";
		}
		else if (mail.length() == 0) {
			responseMessage = "Email cannot be empty string";
		}
		else if (mail.length() < 5) { // shortest e-mail is a@b.c (in theory ..)
			responseMessage = "Email cannot be shorter than 5 symbols";
		}
		else if (mail.indexOf("@") == -1) {
			responseMessage = "Email is missing @ symbol";
		}
		else if (mail.matches(MAIL_REGEX)) {
			responseMessage = "OK";
		}

		PrintWriter writer = response.getWriter();
		writer.print(responseMessage);
		writer.flush();
		writer.close();
	}

}
